package me.qingy.shiro.web.filter;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.qingy.common.utils.ShiroUtils;
import me.qingy.common.utils.SpringUtils;
import me.qingy.core.entity.User;
import me.qingy.core.service.UserOnlineService;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.sql.DataSourceDefinitions;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author qingy
 * @since 2021-05-08
 */
@Slf4j
@Data
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter {

    /**
     * 退出后重定向的地址
     */
    private String loginUrl;

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        try {
            Subject subject = getSubject(request, response);
            String redirectUrl = getRedirectUrl(request, response, subject);
            try {
                User user = ShiroUtils.getSysUser();
                if (user != null) {
                    String loginName = user.getLoginName();
                    // 清理缓存
                    SpringUtils.getBean(UserOnlineService.class).removeUserCache(loginName, ShiroUtils.getSessionId());
                }
                // 退出登录
                subject.logout();
            } catch (SessionException ise) {
                log.error("logout fail.", ise);
            }
            issueRedirect(request, response, redirectUrl);
        } catch (Exception e) {
            log.error("Encountered session exception during logout.  This can generally safely be ignored.", e);
        }
        return false;
    }

    /**
     * 退出跳转URL
     */
    @Override
    protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject) {
        String url = getLoginUrl();
        if (url != null) {
            return url;
        }
        return super.getRedirectUrl(request, response, subject);
    }
}
